/*
 * @Author: 肖思汗 
 * @Date: 2020-08-04 23:46:42 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2021-03-28 18:42:38
 */

import globalStore from "@globalStore";
import ReactMixinComponent from "@ReactMixinComponent";
import React from "react";
import styles from './DragTest.less';
import dragTestStoroe from "./dragTestStore";

interface Props { }

interface State { }

/**
 * 使用 mobxAutoun 生命周期实现 跨组件非重绘的方式修改dom
 *
 * @export
 * @class DragTest
 * @extends {ReactMixinComponent<Props, State>}
 */
export default class DragTest extends ReactMixinComponent<Props, State> {
    constructor(props: Props) {
        super(props);
    }

    mousedown: boolean = false;

    pointDom?: HTMLSpanElement | null;

    // 修改 mobx 数据管理中心的数据
    move(e: React.MouseEvent) {
        if (this.mousedown) {
            const { unZoom } = globalStore;
            dragTestStoroe.top += e.movementY * unZoom;
            dragTestStoroe.left += e.movementX * unZoom;
        }
    }

    componentDidMount() {
        let { mixin_emitter } = this;

        // 使用 mixin_emitter 监听事件时, 组件销毁后 由ReactMixinComponent 统一取消监听
        this.mixin_emitter.on(mixin_emitter.HELLO_WORLD, () => { });

        // 监听公共状态的改变自动执行
        this.mixin_autorun(() => {
            const { top, left } = dragTestStoroe;

            if (this.pointDom) {
                Object.assign(this.pointDom.style, {
                    top: `${top}px`,
                    left: `${left}px`,
                })
            }

        });
    }

    render() {
        return (
            <div
                className={styles.box}
                onMouseMove={(e) => this.move(e)}
                onMouseLeave={() => this.mousedown = false}
                onMouseDown={() => this.mousedown = true}
                onMouseUp={() => this.mousedown = false}
            >
                <span className={styles.point} ref={dom => this.pointDom = dom} />
            </div >
        );
    }

}